package com.yeyks.cncallback.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.SendResult;
import com.aliyun.openservices.ons.api.exception.ONSClientException;
import com.yeyks.common.constants.rocketmq.TopicAndTag;
import com.yeyks.common.dto.mq.EsCbCallBackOrderMessage;
import com.yeyks.common.dto.mq.RefundMessage;
import com.yeyks.config.RocketMqConsumer;
import com.yeyks.config.RocketMqProducerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * CnBooking 订单状态延迟队列
 * @author: dagny
 * @date: 2019/10/14 0014 18:54
 */
@Service
@Slf4j
public class MqCnBookingProducerService {


    @Autowired(required = false)
    private RocketMqProducerConfig rocketMqConfig;

//
//    /**
//     * CN_PUSH自助服务消费
//     * @param data
//     */
//    public void sendSaveReturnCallBack(String data){
//        sendSimpleMsg(data, null, RocketMqConsumer.CN_TOPIC_YYKS_DELAY, RocketMqConsumer.CN_TAG_CNBOOKING_PUSH,false);
//    }

    /**
     * es更新CNBookingOrder 的延迟队列 10秒的延迟
     */
    public void sendCNBookingOrderUpdate(EsCbCallBackOrderMessage msg) {
        sendSimpleMsg(JSONUtil.toJsonStr(msg), 10, TopicAndTag.TOPIC_YYKS_DELAY, TopicAndTag.TAG_CNBOOKING_ORDER_UPATE, true);
    }

    /**
     * 退款信息
     * @param msg
     */
    public void sendCNBookingCancelOrder(RefundMessage msg){
        sendSimpleMsg(JSONUtil.toJsonStr(msg), null, TopicAndTag.TOPIC_YYKS_NORMAL, TopicAndTag.TAG_CNBOOKING_ORDER_CANCEL, true);
    }


    /**
     * 发送简单带延迟的mq消息
     *
     * @param msg
     * @param flag true打印发送日志。 false不打印发送日志
     * @param delayTime 延迟的时间(单位/秒)
     */
    public void sendSimpleMsg(String msg, Integer delayTime, String topic, String tag, Boolean flag) {
        Message message = new Message(topic, tag, msg.getBytes());
        if (null != delayTime) {
            // 延时时间单位为毫秒（ms），指定一个时刻，在这个时刻之后才能被消费，3表示3秒后才能被消费
            delayTime = 1000 * delayTime;
            message.setStartDeliverTime(System.currentTimeMillis() + delayTime);
        }
        try {
            rocketMqConfig.getProducer().send(message);
        } catch (ONSClientException e) {
            // 消息发送失败，需要进行重试处理，可重新发送这条消息或持久化这条数据进行补偿处理
            log.info(new Date() + " Send mq failed! Topic is:" + topic);
            e.printStackTrace();
        }
    }

}
